{% extends "base.html" %}

{% block title %}数据导出 - 数据预处理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12 mb-4">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-primary text-white">
                <h4 class="card-title mb-0">
                    <i class="fas fa-download me-2"></i>数据库结构导出
                </h4>
            </div>
            <div class="card-body">
                <form id="exportForm">
                    <div class="row">
                        <!-- 数据库配置 -->
                        <div class="col-md-6 mb-3">
                            <label for="dbConfig" class="form-label">
                                <i class="fas fa-database me-1"></i>数据库配置 <span class="text-danger">*</span>
                            </label>
                            <select class="form-select" id="dbConfig" name="db_config" required>
                                <option value="">请选择数据库配置</option>
                                {% for name, config in db_configs.items() %}
                                <option value="{{ name }}">{{ name }} ({{ config.db_type.value }} - {{ config.database }})</option>
                                {% endfor %}
                            </select>
                            <div class="form-text">选择要导出的数据库连接配置</div>
                        </div>

                        <!-- AI配置 -->
                        <div class="col-md-6 mb-3">
                            <label for="aiConfig" class="form-label">
                                <i class="fas fa-robot me-1"></i>AI模型配置
                            </label>
                            <select class="form-select" id="aiConfig" name="ai_config">
                                <option value="">不使用AI增强</option>
                                {% for name, config in ai_configs.items() %}
                                <option value="{{ name }}">{{ name }} ({{ config.model_type.value }} - {{ config.model_name }})</option>
                                {% endfor %}
                            </select>
                            <div class="form-text">选择用于智能增强的AI模型（可选）</div>
                        </div>
                    </div>

                    <!-- 导出选项 -->
                    <div class="card border-light mb-3">
                        <div class="card-header bg-light">
                            <h6 class="card-title mb-0">
                                <i class="fas fa-cogs me-1"></i>导出选项
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <h6 class="text-primary">基础选项</h6>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" id="includeSummary" name="include_summary" checked>
                                        <label class="form-check-label" for="includeSummary">
                                            包含汇总信息
                                        </label>
                                    </div>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" id="includeDataInfo" name="include_data_info" checked>
                                        <label class="form-check-label" for="includeDataInfo">
                                            包含数据信息（行数、大小）
                                        </label>
                                    </div>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" id="groupBySchema" name="group_by_schema" checked>
                                        <label class="form-check-label" for="groupBySchema">
                                            按Schema分组
                                        </label>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <h6 class="text-success">AI增强选项</h6>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" id="enableAiEnhancement" name="enable_ai_enhancement">
                                        <label class="form-check-label" for="enableAiEnhancement">
                                            启用AI智能增强
                                        </label>
                                    </div>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" id="enhanceTableComments" name="enhance_table_comments" checked disabled>
                                        <label class="form-check-label" for="enhanceTableComments">
                                            增强表注释
                                        </label>
                                    </div>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" id="enhanceColumnComments" name="enhance_column_comments" checked disabled>
                                        <label class="form-check-label" for="enhanceColumnComments">
                                            增强字段注释
                                        </label>
                                    </div>
                                    <div class="form-check mb-2">
                                        <input class="form-check-input" type="checkbox" id="analyzeRelationships" name="analyze_relationships" checked disabled>
                                        <label class="form-check-label" for="analyzeRelationships">
                                            分析表关系
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 高级筛选 -->
                    <div class="card border-light mb-3">
                        <div class="card-header bg-light">
                            <h6 class="card-title mb-0">
                                <i class="fas fa-filter me-1"></i>高级筛选（可选）
                            </h6>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="schemaFilter" class="form-label">Schema筛选</label>
                                    <select class="form-select" id="schemaFilter" name="schema_filter" multiple>
                                        <!-- 动态加载 -->
                                    </select>
                                    <div class="form-text">选择要导出的Schema（默认全部）</div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="tableFilter" class="form-label">表筛选</label>
                                    <textarea class="form-control" id="tableFilter" name="table_filter" rows="3" 
                                              placeholder="输入表名，每行一个，支持通配符（如：user_*）"></textarea>
                                    <div class="form-text">指定要导出的表（默认全部）</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 操作按钮 -->
                    <div class="text-end">
                        <button type="button" class="btn btn-outline-secondary me-2" id="testConnection">
                            <i class="fas fa-link me-1"></i>测试连接
                        </button>
                        <button type="button" class="btn btn-outline-info me-2" id="previewData">
                            <i class="fas fa-eye me-1"></i>预览数据
                        </button>
                        <button type="submit" class="btn btn-primary" id="startExport">
                            <i class="fas fa-play me-1"></i>开始导出
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- 导出进度模态框 -->
<div class="modal fade" id="exportProgressModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-cog fa-spin me-2"></i>导出进度
                </h5>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted">任务ID: <span id="taskId"></span></span>
                        <span class="badge bg-primary" id="taskStatus">准备中</span>
                    </div>
                    <div class="progress mb-2">
                        <div class="progress-bar progress-bar-striped progress-bar-animated" 
                             role="progressbar" id="progressBar" style="width: 0%">
                        </div>
                    </div>
                    <div class="text-muted" id="progressMessage">初始化任务...</div>
                </div>
                
                <!-- 任务详情 -->
                <div class="card border-light">
                    <div class="card-header bg-light">
                        <h6 class="card-title mb-0">任务详情</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <small class="text-muted">数据库:</small><br>
                                <span id="taskDatabase"></span>
                            </div>
                            <div class="col-md-6">
                                <small class="text-muted">AI模型:</small><br>
                                <span id="taskAiModel"></span>
                            </div>
                        </div>
                        <div class="row mt-2">
                            <div class="col-md-6">
                                <small class="text-muted">开始时间:</small><br>
                                <span id="taskStartTime"></span>
                            </div>
                            <div class="col-md-6">
                                <small class="text-muted">耗时:</small><br>
                                <span id="taskDuration">-</span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 错误信息 -->
                <div class="alert alert-danger mt-3 d-none" id="errorAlert">
                    <h6 class="alert-heading">任务执行失败</h6>
                    <p class="mb-0" id="errorMessage"></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-success d-none" id="downloadResult">
                    <i class="fas fa-download me-1"></i>下载结果
                </button>
                <button type="button" class="btn btn-secondary" id="closeModal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 预览模态框 -->
<div class="modal fade" id="previewModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-eye me-2"></i>数据预览
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="previewContent">
                    <!-- 预览内容 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
$(document).ready(function() {
    let currentTaskId = null;
    let progressInterval = null;
    
    // AI增强选项联动
    $('#enableAiEnhancement').change(function() {
        const enabled = this.checked;
        $('#enhanceTableComments, #enhanceColumnComments, #analyzeRelationships')
            .prop('disabled', !enabled);
        
        if (!enabled) {
            $('#aiConfig').val('');
        }
    });
    
    // AI配置变化时自动启用AI增强
    $('#aiConfig').change(function() {
        if (this.value) {
            $('#enableAiEnhancement').prop('checked', true).trigger('change');
        }
    });
    
    // 数据库配置变化时加载Schema列表
    $('#dbConfig').change(function() {
        const configName = this.value;
        if (configName) {
            loadSchemas(configName);
        } else {
            $('#schemaFilter').empty();
        }
    });
    
    // 测试连接
    $('#testConnection').click(function() {
        const configName = $('#dbConfig').val();
        if (!configName) {
            showAlert('请先选择数据库配置', 'warning');
            return;
        }
        
        const btn = $(this);
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i>测试中...');
        
        $.post(`/api/database/test/${configName}`)
            .done(function(data) {
                if (data.success) {
                    showAlert('数据库连接测试成功', 'success');
                } else {
                    showAlert('连接测试失败: ' + data.message, 'danger');
                }
            })
            .fail(function() {
                showAlert('连接测试失败', 'danger');
            })
            .always(function() {
                btn.prop('disabled', false).html('<i class="fas fa-link me-1"></i>测试连接');
            });
    });
    
    // 预览数据
    $('#previewData').click(function() {
        const configName = $('#dbConfig').val();
        if (!configName) {
            showAlert('请先选择数据库配置', 'warning');
            return;
        }
        
        // TODO: 实现数据预览功能
        showAlert('预览功能开发中...', 'info');
    });
    
    // 表单提交
    $('#exportForm').submit(function(e) {
        e.preventDefault();
        startExport();
    });
    
    // 下载结果
    $('#downloadResult').click(function() {
        if (currentTaskId) {
            window.location.href = `/api/download/${currentTaskId}`;
        }
    });
    
    // 关闭模态框
    $('#closeModal').click(function() {
        if (progressInterval) {
            clearInterval(progressInterval);
            progressInterval = null;
        }
        $('#exportProgressModal').modal('hide');
    });
    
    function loadSchemas(configName) {
        $.get(`/api/database/schemas/${configName}`)
            .done(function(data) {
                if (data.success) {
                    const select = $('#schemaFilter');
                    select.empty();
                    
                    data.schemas.forEach(schema => {
                        select.append(`<option value="${schema}">${schema}</option>`);
                    });
                }
            })
            .fail(function() {
                showAlert('加载Schema列表失败', 'warning');
            });
    }
    
    function startExport() {
        const formData = {
            db_config: $('#dbConfig').val(),
            ai_config: $('#aiConfig').val(),
            options: {
                include_summary: $('#includeSummary').is(':checked'),
                include_data_info: $('#includeDataInfo').is(':checked'),
                group_by_schema: $('#groupBySchema').is(':checked'),
                enable_ai_enhancement: $('#enableAiEnhancement').is(':checked'),
                enhance_table_comments: $('#enhanceTableComments').is(':checked'),
                enhance_column_comments: $('#enhanceColumnComments').is(':checked'),
                analyze_relationships: $('#analyzeRelationships').is(':checked'),
                schema_filter: $('#schemaFilter').val(),
                table_filter: $('#tableFilter').val().split('\n').filter(t => t.trim())
            }
        };
        
        if (!formData.db_config) {
            showAlert('请选择数据库配置', 'warning');
            return;
        }
        
        // 提交任务
        $.ajax({
            url: '/api/export/start',
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(formData)
        })
        .done(function(data) {
            if (data.success) {
                currentTaskId = data.task_id;
                showProgressModal();
                startProgressMonitoring();
            } else {
                showAlert('启动导出任务失败: ' + data.message, 'danger');
            }
        })
        .fail(function() {
            showAlert('启动导出任务失败', 'danger');
        });
    }
    
    function showProgressModal() {
        $('#taskId').text(currentTaskId);
        $('#taskDatabase').text($('#dbConfig option:selected').text());
        $('#taskAiModel').text($('#aiConfig option:selected').text() || '未使用');
        $('#taskStartTime').text(new Date().toLocaleString());
        $('#taskDuration').text('-');
        
        $('#progressBar').css('width', '0%').text('0%');
        $('#progressMessage').text('初始化任务...');
        $('#taskStatus').removeClass().addClass('badge bg-primary').text('准备中');
        
        $('#errorAlert').addClass('d-none');
        $('#downloadResult').addClass('d-none');
        
        $('#exportProgressModal').modal('show');
    }
    
    function startProgressMonitoring() {
        progressInterval = setInterval(function() {
            updateProgress();
        }, 2000); // 每2秒检查一次
    }
    
    function updateProgress() {
        if (!currentTaskId) return;
        
        $.get(`/api/tasks/${currentTaskId}/status`)
            .done(function(data) {
                if (data.success) {
                    const task = data.task;
                    updateProgressUI(task);
                    
                    if (task.status === 'completed' || task.status === 'failed') {
                        if (progressInterval) {
                            clearInterval(progressInterval);
                            progressInterval = null;
                        }
                    }
                }
            });
    }
    
    function updateProgressUI(task) {
        const progress = task.progress || 0;
        $('#progressBar').css('width', progress + '%').text(progress + '%');
        $('#progressMessage').text(task.message || '');
        
        // 更新状态
        const statusClass = getStatusClass(task.status);
        const statusText = getStatusText(task.status);
        $('#taskStatus').removeClass().addClass(`badge bg-${statusClass}`).text(statusText);
        
        // 更新耗时
        if (task.start_time) {
            const duration = Math.floor((new Date() - new Date(task.start_time)) / 1000);
            $('#taskDuration').text(formatDuration(duration));
        }
        
        // 处理完成状态
        if (task.status === 'completed') {
            $('#downloadResult').removeClass('d-none');
            showAlert('导出完成！', 'success');
        } else if (task.status === 'failed') {
            $('#errorAlert').removeClass('d-none');
            $('#errorMessage').text(task.error || '未知错误');
        }
    }
    
    function getStatusClass(status) {
        const map = {
            'starting': 'secondary',
            'connecting': 'info',
            'extracting': 'warning',
            'loading_ai': 'info',
            'enhancing': 'primary',
            'exporting': 'warning',
            'completed': 'success',
            'failed': 'danger'
        };
        return map[status] || 'secondary';
    }
    
    function getStatusText(status) {
        const map = {
            'starting': '启动中',
            'connecting': '连接数据库',
            'extracting': '提取结构',
            'loading_ai': '加载AI模型',
            'enhancing': 'AI增强中',
            'exporting': '导出Excel',
            'completed': '已完成',
            'failed': '失败'
        };
        return map[status] || '未知';
    }
    
    function formatDuration(seconds) {
        if (seconds < 60) {
            return seconds + '秒';
        } else if (seconds < 3600) {
            return Math.floor(seconds / 60) + '分' + (seconds % 60) + '秒';
        } else {
            const hours = Math.floor(seconds / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            return hours + '时' + minutes + '分';
        }
    }
    
    function showAlert(message, type) {
        const alertHtml = `
            <div class="alert alert-${type} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        $('.container-fluid').prepend(alertHtml);
        
        // 自动消失
        setTimeout(function() {
            $('.alert').first().alert('close');
        }, 5000);
    }
});
</script>
{% endblock %}